Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

340
Visualizações
Error: Module name "fs" has not been loaded yet for context. Trying to write in a JSON file

Hi everyone c: I've been working in a Node.js project where I bring data from a JSON file and use it with an API to bring weather, and other things, I'm trying to write the new data into another JSON file using require.js but it does not seems to work, here is my code, hope you can help me :)

const fs = require('fs');
var myObject = {  
                Latitud: data.coord.lat,
                Longitud: data.coord.lon,
                Temperatura: data.main.temp, 
                Ciudad: data.name, 
                Humedad: data.main.humidity,
                Descripción: data.weather[0].description,
                Viento: data.wind.speed,
            };
            // convert JSON object to a string
            const _myObject = JSON.stringify(myObject);
            // write file to disk
            fs.writeFile('../js/datareceived.json', _myObject, 'utf8', (err) => {
                if (err) {
                    console.log(`Error writing file: ${err}`);
                } else {
                    console.log(`File is written successfully!`);
                }

            });

and here is the full script

async function calcWeather(){ 
    const info = await fetch('../js/data.json') // fetch editable c:
    .then(function(response) {
        return response.json();
    });
    for (var i in info) {
        const lat = info[i][0].latjson;
        const long = info[i][0].lonjson;
        const fs = require('fs');
        const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
        
        fetch(base)
        .then((responses) => {
        return responses.json();
        })
        .then((data) => {
            var myObject = {  
                Latitud: data.coord.lat,
                Longitud: data.coord.lon,
                Temperatura: data.main.temp, 
                Ciudad: data.name, 
                Humedad: data.main.humidity,
                Descripción: data.weather[0].description,
                Viento: data.wind.speed,
            };
            // convert JSON object to a string
            const _myObject = JSON.stringify(myObject);
            // write file to disk
            fs.writeFile('../js/datareceived.json', _myObject, 'utf8', (err) => {
                if (err) {
                    console.log(`Error writing file: ${err}`);
                } else {
                    console.log(`File is written successfully!`);
                }

            });
        });
        
    }
    
};

and here is the way I load in my html

<script src = "./node_modules/requirejs/require.js"></script>
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda